<template>
  <el-drawer
    :append-to-body="true"
    :wrapperClosable="false"
    :title="title"
    size="1000px"
    :visible="open"
    @close="handleClose"
  >
    <div class="dialog-container" v-loading="formLoading">
      <div class="dialog-content">
        <el-form
          @submit.native.prevent
          ref="form"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <div class="flex_center_form">
            <el-form-item label="题型" prop="topicType">
              <el-select
                class="w_herf"
                filterable
                :disabled="enterType=='tactics'"
                @change="changeTopicType"
                v-model.number="form.topicType"
                placeholder="请选择题型"
              >
                <el-option
                  v-for="dict in dict.type.topic_type"
                  :key="Number(dict.value)"
                  :label="dict.label"
                  :value="Number(dict.value)"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="难度" prop="difficulty">
              <el-select
                class="w_herf"
                filterable
                v-model.number="form.difficulty"
                placeholder="请选择难度"
              >
                <el-option
                  v-for="dict in dict.type.topic_difficulty"
                  :key="Number(dict.value)"
                  :label="dict.label"
                  :value="Number(dict.value)"
                />
              </el-select>
            </el-form-item>
          </div>
          <el-form-item label="知识点" prop="indexId">
            <el-cascader
              placeholder="请选择知识点"
              class="w_all"
              :disabled="enterType=='tactics'"
              v-removeAriaHidden
              v-model="form.indexId"
              :options="courseIndexTree"
              filterable
              clearable
              :props="{
                  expandTrigger: 'click',
                  checkStrictly: true,
                  emitPath: false,
                  value: 'id',
                  label: 'name',
               }"
            >
            </el-cascader>
          </el-form-item>
          <el-form-item label="题干" prop="content">
            <div class="flex_center">
              <div style="position:relative;flex:1" @click="getByEditor('content',3)"
                   :class="{'preview_content':$isIncludesHtml(form.content)}"
              >
                <el-input
                  :disabled="$isIncludesHtml(form.content)"
                  type="textarea"
                  id="textarea"
                  v-model="form.content"
                  placeholder="请输入题干"
                  @blur="campaignNameBlur"
                  :autosize="{ minRows: 3, maxRows: 10 }"
                />
                <div class="btn_box" @click.stop="getByEditor('content',2)" v-if="$isIncludesHtml(form.content)">
                  <svg-icon class-name="edit_icon" icon-class="edit"></svg-icon>
                </div>
                <div class="btn_box" v-else @click="getByEditor('content',1)">
                  <svg-icon class-name="fwb_icon" icon-class="fwb_init"></svg-icon>
                </div>
              </div>
            </div>
            <div v-if="form.topicType == 3 && !$isIncludesHtml(form.content)">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-plus"
                plain
                @click="handleAddBlank"
              >插入填空符
              </el-button>
              <span class="ml10"><span class="color_red">*</span>填空符由英文括号以及三个下划线组成,例: ___</span>
            </div>
          </el-form-item>
          <div class="table_content" v-if="allTypes.includes(form.topicType)">
            <div class="label">
              <span>*</span>{{ form.topicType == 3 ? '填空项' : '选项' }}
            </div>
            <div class="main">
              <el-table
                :data="form.ccTopicOptionList"
                ref="multipleTable"
                :header-cell-style="tableHeaderStyle"
                :row-style="rowStyle"
                class="cum_table"
                row-key="id"
              >
                <!--  选择题选择正确选项      -->
                <el-table-column width="60px" align="center" v-if="allTypes.includes(form.topicType)">
                  <template slot-scope="scope">
                    <el-checkbox @change="changeIstrue(scope.row)" class="selected_box"
                                 v-model="scope.row.trueOption"
                    ></el-checkbox>
                  </template>
                </el-table-column>
                <!--  拖拽排序      -->
                <el-table-column prop="sort" label="拖拽排序" width="120px" align="center">
                  <template slot-scope="scope">
                    <div class="moved">
                      <svg-icon class-name="darg_svg" icon-class="darg_svg"></svg-icon>
                    </div>
                  </template>
                </el-table-column>
                <!--  填空题      -->
                <el-table-column
                  width="100px"
                  label="答案"
                  prop="optionIndexStr"
                  v-if="form.topicType == 3"
                >
                  <template slot-scope="scope">
                    <span>填空{{ scope.$index + 1 }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  width="120px"
                  label="选项"
                  prop="optionIndexStr"
                  v-if="choiceTypes.includes(form.topicType)"
                >
                  <template slot-scope="scope">
                    <span>{{ labelList[scope.$index] }}</span>
                  </template>
                </el-table-column>
                <el-table-column>
                  <template slot="header" v-if="form.topicType === 3">
                    <div class="header_btns">
                      <div @click="handleSetGroup" class="set_button">
                        <svg-icon class-name="group_icon" icon-class="set_group"></svg-icon>
                        设置分组
                      </div>
                      <div @click="handleDeleteGroup" class="set_button">
                        <svg-icon class-name="group_icon" icon-class="close_group"></svg-icon>
                        取消分组
                      </div>
                      <el-tooltip placement="top">
                        <div slot="content" class="tips-content text-tips-content">
                          <span>提示</span><br/>
                          <div class="rule-box">
                            1、每一空支持多个答案，答案之间使用英文符号&进行连接,例: 八&8<br/>
                            2、支持多个相邻的填空之间不区分先后顺序，将不区分先后顺序的相邻答案前面勾选框勾选上，<br/>
                            点击设置分组按钮，将勾选的答案设置为一组<br/>
                            3、设置分组后，同一组答案的背景色相同，不同组答案的背景色不同<br/>
                          </div>
                        </div>
                        <i class="el-icon-info shou"/>
                      </el-tooltip>
                    </div>
                  </template>
                  <template slot="header" v-if="choiceTypes.includes(form.topicType)">
                    <span>勾选设置正确答案</span>
                  </template>
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="`ccTopicOptionList.${scope.$index}.optionValue`"
                      :rules="rules.optionValue"
                      style="margin: 0"
                      label-width="0"
                    >
                      <div v-if="form.topicType!=3" @click="getByEditor('options',3,scope.row,scope.$index)"
                           :class="{'preview_content': $isIncludesHtml(scope.row.optionValue)}"
                      >
                        <el-input
                          :disabled="$isIncludesHtml(scope.row.optionValue)"
                          v-model="scope.row.optionValue"
                          placeholder="请输入选项内容"
                        ></el-input>
                      </div>
                      <template v-if="form.topicType==3">
                        <el-input
                          v-if="!$isIncludesHtml(scope.row.optionValue)"
                          v-model="scope.row.optionValue"
                          placeholder="请输入填空题答案"
                        ></el-input>
                        <div v-else class="formula_text" v-html="$renderedDescription(scope.row.optionValue)"></div>
                      </template>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column width="160px" align="center">
                  <template slot="header">
                    <div class="header_add_box">
                      <div @click="addOption" class="add_option">
                        <svg-icon class-name="add_icon" icon-class="add_svg"></svg-icon>
                        添加选项
                      </div>
                    </div>
                  </template>
                  <template slot-scope="scope">
                    <div class="header_content_box">
                      <div class="icon_box" @click="deleteOption(scope.$index)">
                        <i class="el-icon-delete"></i>
                      </div>
                      <template v-if="form.topicType!=3">
                        <div v-if="$isIncludesHtml(scope.row.optionValue)" @click="getByEditor('options',2,scope.row,scope.$index)"
                             class="icon_box"
                        >
                          <i class="el-icon-edit"></i>
                        </div>
                        <div v-else @click="getByEditor('options',1,scope.row,scope.$index)" class="icon_box">
                          <svg-icon class-name="fwb_icon" icon-class="fwb_init"></svg-icon>
                        </div>
                      </template>
                      <template v-if="form.topicType==3">
                        <div v-if="!$isIncludesHtml(scope.row.optionValue) && !scope.row.optionValue"
                             @click="getValueByFormula(scope.$index)" class="icon_box"
                        >
                          <svg-icon class-name="formula_icon" icon-class="formula_scg"></svg-icon>
                        </div>
                      </template>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <!--判断题区块 -->
          <div v-if="form.topicType == 2">
            <el-form-item label="答案" prop="right">
              <el-radio-group v-removeAriaHidden v-model="form.right" ref="radioGroup">
                <el-radio :label="true">正确</el-radio>
                <el-radio :label="false">错误</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <el-form-item label="答案" prop="resolve" v-if="QaTypes.includes(form.topicType)">
            <div class="flex_center">
              <div style="position:relative;flex:1" @click="getByEditor('answer',3)"
                   :class="{'preview_content': form.answer && $isIncludesHtml(form.answer)}"
              >
                <el-input
                  :disabled="$isIncludesHtml(form.answer)"
                  v-model="form.answer"
                  type="textarea"
                  placeholder="请输入内容"
                  :autosize="{ minRows: 3, maxRows: 6 }"
                />
              </div>
              <div class="btn_box" @click.stop="getByEditor('answer',2)" v-if="$isIncludesHtml(form.answer)">
                <svg-icon class-name="edit_icon" icon-class="edit"></svg-icon>
              </div>
              <div class="btn_box" v-else @click="getByEditor('answer',1)">
                <svg-icon class-name="fwb_icon" icon-class="fwb_init"></svg-icon>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="解析" prop="resolve">
            <div class="flex_center">
              <div style="position:relative;flex:1" @click="getByEditor('resolve',3)"
                   :class="{'preview_content': form.resolve && $isIncludesHtml(form.resolve)}"
              >
                <el-input
                  :disabled="$isIncludesHtml(form.resolve)"
                  v-model="form.resolve"
                  type="textarea"
                  placeholder="请输入内容"
                  :autosize="{ minRows: 3, maxRows: 6 }"
                />
                <div class="btn_box" @click.stop="getByEditor('resolve',2)" v-if="$isIncludesHtml(form.resolve)">
                  <svg-icon class-name="edit_icon" icon-class="edit"></svg-icon>
                </div>
                <div class="btn_box" v-else @click="getByEditor('resolve',1)">
                  <svg-icon class-name="fwb_icon" icon-class="fwb_init"></svg-icon>
                </div>
              </div>
            </div>
          </el-form-item>
<!--          <el-form-item-->
<!--            label="是否需要设备"-->
<!--            prop="needDevice"-->
<!--            v-show="form.topicType == 5"-->
<!--          >-->
<!--            <el-select-->
<!--              filterable-->
<!--              v-model="form.needDevice"-->
<!--              placeholder="是否需要设备"-->
<!--              clearable-->
<!--            >-->
<!--              <el-option-->
<!--                v-for="dict in dict.type.need_device"-->
<!--                :key="dict.value"-->
<!--                :label="dict.label"-->
<!--                :value="dict.value"-->
<!--              />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
        </el-form>
      </div>
      <div class="bottom_box" v-if="openType=='add'">
        <div></div>
        <div class="btns">
          <el-button @click="handleClose">关闭</el-button>
          <el-button type="primary" @click="handleSubmit(1)">确定</el-button>
        </div>
      </div>
      <div class="bottom_box" v-if="openType=='edit'">
        <div class="signs">
          <div class="sign">保存并同步：同步更新题库中的题目内容及其他试卷引用的该题目内容</div>
          <div class="sign">保存并新增：新增一道题目至题库，不影响题库中的原题目</div>
        </div>
        <div class="btns">
          <el-button @click="handleClose">关闭</el-button>
          <el-button type="primary" @click="handleSubmit(2)">保存并同步</el-button>
          <el-button type="primary" @click="handleSubmit(3)">保存并新增</el-button>
        </div>

      </div>
      <!--  编辑弹窗  -->
      <editDrawer :show.sync="showDrawer" :requiredEditor="requiredEditor" :openType="propOpenType" :topicType="propTopicType" :propEditorValue="propEditorValue"
                  @sureConfirm="sureConfirm"
      ></editDrawer>
      <!--  插入公式  -->
      <addFormulaOptionDrawer :open.sync="showFormulaDrawer" @formulaReturn="formulaReturn"></addFormulaOptionDrawer>
    </div>
  </el-drawer>
</template>

<script>
import { v4 as uuidv4 } from 'uuid'
import wangEditor from '@/components/Editor/wangEditor'
import editDrawer from '@/views/tea_course/components/editDrawer'
import addFormulaOptionDrawer from './addFormulaOptionDrawer'
import { getCourseIndexTreesApi, getTopicInfoApi } from '@/api/ExaminationModule'
import Sortable from 'sortablejs'

export default {
  name: 'addTopicDrawer',
  components: {
    wangEditor,
    addFormulaOptionDrawer,
    editDrawer
  },
  dicts: ['topic_type', 'topic_difficulty', 'need_device'],
  props: {
    open: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '手动录入试题'
    },
    courseId: {
      type: [String, Number],
      required: true,
      default: ''
    },
    topicId: {
      type: [String, Number],
      default: ''
    },
    topicType: {
      type: [String, Number],
      default: ''
    },
    indexId: {
      type: [String, Number],
      default: ''
    },
    enterType: {
      type: [String, Number],
      default: ''
    },
    openType: {
      type: String,
      default: 'add'
    }
  },
  data() {
    return {
      requiredEditor: true,
      showFormulaDrawer: false,
      formLoading: false,
      tableHeaderStyle: {
        'background-color': '#f8f8f9',
        'color': '#333333',
        'font-size': '14px',
        'font-family': 'PingFangSC, PingFang SC',
        'font-weight': '400'
      },
      // 选择题选项
      labelList: this.$store.getters.EN,
      //背景色列表
      colorList: ['#ffffff', '#eaf8e8', '#fff2cc', '#ffe6e6', '#e6f7ff', '#f3e5f5', '#fff0b3', '#f0ffff', '#ffffcd', '#d9ead3', '#fce5cd'],
      //记录当前选项下标
      nowOptionIndex: '',
      //记录当前打开富文本录入组件类型
      openString: '',
      //富文本录入类型 1：添加 2：编辑 3：查看
      propOpenType: 1,
      //富文本录入抽屉状态
      showDrawer: false,
      //富文本录入组件---内容
      propEditorValue: '',
      //富文本录入组件---试题类型
      propTopicType: '',
      //知识点列表
      courseIndexTree: [],
      //光标位置
      cursorPosition: 0,
      //选择题类型
      choiceTypes: [0, 1],
      //表格类型
      allTypes: [0, 1, 3],
      //简答题操作题类型
      QaTypes: [4, 5],
      //表单验证规则
      rules: {
        optionValue: { required: true, message: '请输入选项内容' },
        topicType: { required: true, message: '请选择试题类型', trigger: 'change' },
        difficulty: { required: true, message: '请选择难度', trigger: 'change' },
        indexId: { required: true, message: '请选择知识点', trigger: 'change' },
        content: { required: true, validator: this.$checkContent, trigger: 'blur' },
        right: { required: true, message: '请选择答案', trigger: 'change' }
      },
      //表单参数
      form: {
        topicType: '',
        indexId: '',
        difficulty: '',
        content: '',
        right: true,
        answer: '',
        resolve: '',
        ccTopicOptionList: []
      }
    }
  },
  watch: {
    open(val) {
      if (val) {
        this.reSet()
        if (this.enterType == 'tactics') {
          this.form.topicType = this.topicType
        }
        this.getCourseIndexTrees(this.courseId)
        if (this.openType == 'edit') {
          this.getFormInfo(this.topicId)
        }
        console.log(this.indexId)
        this.form.indexId = this.indexId
      }
    },
    'form.ccTopicOptionList': {
      handler(val) {
        if (val.length > 0 && this.allTypes.includes(this.form.topicType)) {
          this.$nextTick(() => {
            this.openDrag()
          })
        }
      },
      deep: true
    }

  },
  methods: {
    getValueByFormula(index) {
      this.showFormulaDrawer = true
      this.nowOptionIndex = index
    },
    formulaReturn(e) {
      this.form.ccTopicOptionList[this.nowOptionIndex].optionValue = e
      this.nowOptionIndex = ''
    },
    changeTopicType() {
      if (this.choiceTypes.includes(this.form.topicType)) {
        let arr = []
        for (let i = 0; i < 4; i++) {
          let id = uuidv4().replace(/-/g, '')
          arr.push({
            optionValue: '',
            trueOption: false,
            disabled: false,
            group: null,
            id: id
          })
        }
        this.form.ccTopicOptionList = arr
      } else {
        this.form.ccTopicOptionList = []
      }
    },
    async getFormInfo(topicId) {
      this.formLoading = true
      try {
        let res = await getTopicInfoApi(topicId)
        const { code, data } = res
        if (code == 200) {
          if (data.topicType == 2) {
            data.right = data.answer == '正确'
          }
          this.form = data
        }
      } catch (e) {
        console.error(e)
      } finally {
        this.formLoading = false
      }
    },
    //设置分组
    handleSetGroup() {
      let arr = this.form.ccTopicOptionList
      if (arr.filter((item) => item.trueOption).length < 2) {
        this.$modal.msgWarning('请勾选至少两个答案进行分组')
        return
      }
      let hasIsolatedTrueOption = false
      let lastTrueIndex = -2 // 初始值设置为-2，确保第一个trueOption不会被认为不连续
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].trueOption) {
          if (lastTrueIndex !== i - 1 && lastTrueIndex !== -2) {
            hasIsolatedTrueOption = true
            break
          }
          lastTrueIndex = i
        }
      }
      if (hasIsolatedTrueOption) {
        this.$modal.msgWarning('分为一组的答案必须相邻')
        return
      }
      // 找出当前最大的分组编号
      const maxGroup = Math.max(0, ...arr.map(item => item.group || 0))
      // 计算新的分组编号
      const newGroup = maxGroup === 10 ? (() => {
        for (let j = 1; j <= 10; j++) {
          if (!arr.some(item => item.group === j)) {
            return j
          }
        }
        return maxGroup // 所有1-10都被占用时保持原样
      })() : maxGroup + 1
      // 更新需要分组的项
      arr.forEach(item => {
        if (item.trueOption) {
          item.group = newGroup
          item.trueOption = false
        }
      })
    },
    //取消分组
    handleDeleteGroup() {
      if (this.form.ccTopicOptionList.length == 0) {
        return
      }
      this.form.ccTopicOptionList.forEach(item => {
        item.group = null
        item.trueOption = false
      })
    },
    //对同一分组的填空题答案，设置行颜色
    rowStyle({ row }) {
      //判断row是否有group属性
      if (row.group) {
        return { 'background-color': this.colorList[row.group], cursor: 'pointer' }
      } else {
        return { 'background-color': this.colorList[0], cursor: 'pointer' }
      }
    },
    //使el-table可以拖拽排序
    openDrag() {
      const el = this.$refs.multipleTable.$el.querySelector('.el-table__body-wrapper tbody')
      Sortable.create(el, {
        handle: '.moved', // 拖拽元素类名
        disabled: false, // 拖拽不可用? false 启用
        ghostClass: 'sortable-ghost', //拖拽样式
        animation: 150, // 拖拽延时，效果更好看
        onEnd: (e) => {
          let arr = this.form.ccTopicOptionList // 获取表数据
          arr.splice(e.newIndex, 0, arr.splice(e.oldIndex, 1)[0]) // 数据处理
        }
      })
    },
    addOption() {
      if (!this.form.content || this.form.content === '<p><br></p>') {
        this.$modal.msgWarning('请先输入题干内容!')
        return
      }
      const blankMatches = this.form.content.match(/___/g)
      const blankCount = blankMatches ? blankMatches.length : 0
      const optionCount = this.form.ccTopicOptionList.length
      if (!blankMatches && this.form.topicType == 3) {
        this.$modal.msgWarning('请先设置填空符!')
        return
      }
      if (this.form.topicType == 3 && optionCount >= blankCount) {
        this.$modal.msgWarning('选项数量不能大于填空数量！')
        return
      }
      let id = uuidv4().replace(/-/g, '')
      this.form.ccTopicOptionList.push({
        optionValue: '',
        trueOption: false,
        disabled: false,
        group: null,
        id: id
      })
    },
    deleteOption(index) {
      this.form.ccTopicOptionList.splice(index, 1)
    },
    changeIstrue(row) {
      if (this.form.topicType == 0) {
        for (const ccTopicOptionListElement of this.form.ccTopicOptionList) {
          ccTopicOptionListElement.trueOption = row.id == ccTopicOptionListElement.id
        }
      }
    },
    //回显富文本内容
    sureConfirm(e) {
      if (this.openString == 'options') {
        this.form.ccTopicOptionList[this.nowOptionIndex].optionValue = e
        this.form.ccTopicOptionList[this.nowOptionIndex].disabled = true
        this.nowOptionIndex = ''
      }
      if (this.openString == 'content') {
        this.form.content = e
      }
      if (this.openString == 'resolve') {
        if (e == '<p><br></p>'){
          this.form.resolve = ''
        }else {
          this.form.resolve = e
        }
      }
      if (this.openString == 'answer') {
        if (e == '<p><br></p>'){
          this.form.answer = ''
        }else {
          this.form.answer = e
        }
      }
      this.openString = ''
      this.propTopicType = ''
    },
    //获取光标位置
    campaignNameBlur(e) {
      this.cursorPosition = e.srcElement.selectionStart
    },
    //富文本录入
    getByEditor(openString, type, row, index) {
      this.openString = openString
      if (openString == 'options') {
        if (type == 3 && !this.$isIncludesHtml(row.optionValue)) {
          return
        }
        this.nowOptionIndex = index
        this.propEditorValue = row.optionValue
        this.propOpenType = type
        this.requiredEditor = true
        this.showDrawer = true
      }
      if (openString == 'content') {
        if (type == 3 && !this.$isIncludesHtml(this.form.content)) {
          return
        }
        if (type == 1) {
          this.$refs.form.clearValidate('content')
        }
        this.propEditorValue = this.form.content
        this.propTopicType = this.form.topicType
        this.propOpenType = type
        this.requiredEditor = true
        this.showDrawer = true
      }
      if (openString == 'resolve') {
        if (type == 3 && !this.$isIncludesHtml(this.form.resolve)) {
          return
        }
        this.propEditorValue = this.form.resolve
        this.propOpenType = type
        this.requiredEditor = false
        this.showDrawer = true
      }
      if (openString == 'answer') {
        if (type == 3 && !this.$isIncludesHtml(this.form.answer)) {
          return
        }
        this.propEditorValue = this.form.answer
        this.propOpenType = type
        this.requiredEditor = false
        this.showDrawer = true
      }
    },
    //光标处插入填空符
    handleAddBlank() {
      let num = this.cursorPosition
      let cont = this.form.content
      if (num > 0) {
        //插入到指定光标处
        let left = cont.slice(0, num)
        let right = cont.slice(num)
        this.form.content = left + '___' + right
        this.cursorPosition = num + 3
      } else {
        //没有指定插入直接添加到最后
        this.cursorPosition += 3
        this.form.content += '___'
      }

      let id = uuidv4().replace(/-/g, '')
      let obj = {
        optionValue: '',
        trueOption: false,
        disabled: false,
        group: null,
        id: id
      }
      // 联动在count处添加option
      this.form.ccTopicOptionList.push(obj)
    },
    //获取知识点列表
    async getCourseIndexTrees(id) {
      try {
        let res = await getCourseIndexTreesApi(id)
        const { code, data } = res
        if (code == 200) {
          this.courseIndexTree = data
        }
      } catch (e) {
        console.log(e)
      }
    },
    //关闭抽屉
    handleClose() {
      this.$emit('update:open', false)
    },
    reSet() {
      this.resetForm('form')
      this.form = {
        topicType: '',
        indexId: '',
        difficulty: '',
        content: '',
        right: true,
        answer: '',
        resolve: '',
        ccTopicOptionList: []
      }
    },
    //提交表单内容到父组件
    handleSubmit(type) {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.choiceTypes.includes(this.form.topicType)) {
            if (this.form.ccTopicOptionList.length < 2) {
              this.$modal.msgWarning('选项不能少于两个')
              return
            }
            if (this.form.ccTopicOptionList.filter((item) => item.trueOption).length === 0) {
              this.$modal.msgWarning('请勾选正确答案')
              return
            }
            // 校验 optionValue 不能重复（优化后）
            const optionValues = this.form.ccTopicOptionList.map(item => item.optionValue)
            const uniqueValues = new Set(optionValues)
            if (uniqueValues.size !== optionValues.length) {
              this.$modal.msgWarning('识别到选项内容有重复，请检查后重新输入')
              return
            }
            if (this.form.topicType == 1 && this.form.ccTopicOptionList.filter((item) => item.trueOption).length < 2) {
              this.$modal.msgWarning('多选题答案至少为2个')
              return
            }
          }
          if (this.form.topicType == 2) {
            this.form.ccTopicOptionList = this.form.right ? [{
              optionLabel: 'A',
              optionValue: '正确',
              trueOption: true
            }] : [{ optionLabel: 'A', optionValue: '错误', trueOption: true }]
          }
          if (this.QaTypes.includes(this.form.topicType)) {
            this.form.ccTopicOptionList = [{ optionLabel: 'A', optionValue: this.form.answer, trueOption: true }]
          }

          if (this.form.topicType == 3) {
            const blankMatches = this.form.content.match(/___/g)
            const blankCount = blankMatches ? blankMatches.length : 0
            const optionCount = this.form.ccTopicOptionList.length
            if (!blankMatches) {
              this.$modal.msgWarning('请先设置填空符!')
              return
            }
            if (optionCount != blankCount) {
              this.$modal.msgWarning('选项必须与填空数一致')
              return
            }
            this.form.ccTopicOptionList.forEach((option) => {
              option.trueOption = true
            })
          }
          this.form.ccTopicOptionList.forEach((item, index) => {
            item.optionLabel = this.labelList[index]
            item.id = null
          })
          let params = {
            ...this.form,
            optionCount: this.form.ccTopicOptionList.length
          }
          params.type = type
          if (type == 2) {
            this.$confirm('<span style="color: #e95756">是否确定变更题库中的题目内容及其他试卷中的该题目内容？</span>', '同步更新确认', {
              dangerouslyUseHTMLString: true,
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.$emit('submit', params)
              this.handleClose()
            }).catch(() => {
              this.$modal.msgInfo('已取消')
            })
          } else {
            this.$emit('submit', params)
            this.handleClose()
          }
        } else {
          this.$modal.msgWarning('请按规范填写标红文本框内容')
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
@import "../../../assets/styles/mixin.scss";

.dialog-container {
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;

  .dialog-content {
    width: 100%;
    padding: 20px 0 0;
    box-sizing: border-box;
    height: calc(100vh - 174px);
    overflow: auto;

    .flex_center {
      display: flex;

      .btn_box {
        z-index: 5;
        width: 32px;
        height: 32px;
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        bottom: 6px;
        right: 6px;
        margin-left: 10px;
        user-select: none;
        cursor: pointer;
        border-radius: 6px;

        &:hover {
          background: #f1f1f1;
        }

        .fwb_icon {
          font-size: 20px;
        }

        .edit_icon {
          color: #28b28b;
          font-size: 20px;
        }
      }
    }

    .table_content {
      width: 100%;
      display: flex;
      margin-bottom: 22px;

      .label {
        width: 100px;
        padding: 0 12px 0 0;
        box-sizing: border-box;
        font-size: 14px;
        color: #606266;
        text-align: right;
        font-weight: bold;

        span {
          color: #f67878;
          margin-right: 4px
        }
      }

      .main {
        flex: 1;

        .cum_table {
          width: 857px;
          height: 100%;
          border-radius: 8px;
          border: 1px solid #E8EAEB;

          .moved {
            padding: 6px;
            box-sizing: border-box;
            cursor: move;
            user-select: none;

            &:active {
              cursor: move !important;
            }

            .darg_svg {
              font-size: 20px;
              color: #000000;
            }
          }

          .header_btns {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: flex-end;
            gap: 0 10px;

            .set_button {
              @include plain_hover(#ffffff, #333333, #ffffff) {
                width: 96px;
                height: 32px;
                border-radius: 8px;
                border: 1px solid #DDDDDD;
                font-family: PingFangSC, PingFang SC, sans-serif;
                font-weight: 400;
                font-size: 14px;
                color: #333333;
              }
            }
          }

          .header_add_box {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: flex-end;

            .add_option {
              @include plain_hover(#ffffff, #28B28B, #ffffff) {
                width: 96px;
                height: 32px;
                border-radius: 8px;
                border: 1px solid #DDDDDD;
                font-family: PingFangSC, PingFang SC, sans-serif;
                font-weight: 400;
                font-size: 14px;
                color: #28B28B;
              }
            }
          }

          .header_content_box {
            width: 100%;
            display: flex;
            gap: 0 10px;
            justify-content: center;

            .icon_box {
              width: 32px;
              height: 32px;
              display: flex;
              justify-content: center;
              align-items: center;
              user-select: none;
              cursor: pointer;
              border-radius: 6px;

              &:hover {
                background: #f1f1f1;
              }

              .el-icon-delete {
                font-size: 20px;
                color: #f67878;
              }

              .el-icon-edit {
                font-size: 20px;
                color: #28b28b;
              }

              .fwb_icon {
                font-size: 20px;
              }
            }
          }
        }

        ::v-deep .el-table:before {
          height: 0;
        }
      }
    }
  }

  .bottom_box {
    margin-top: 20px;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .signs {
      display: flex;
      flex-direction: column;

      .sign {
        font-family: PingFangSC, PingFang SC, sans-serif;
        font-weight: 400;
        font-size: 14px;
        color: #e95756;
      }
    }

    .btns {
      display: flex;
      justify-content: flex-end;
    }
  }
}

.preview_content {
  position: relative;
  cursor: pointer;

  &:hover {
    user-select: none;

    &:after {
      content: '预览';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 4px;
      color: #999999;
      background: rgba(0, 0, 0, .2);
    }
  }
}

.formula_icon {
  font-size: 20px;
  color: #1677ff;
}

.color_red {
  margin-right: 2px;
  color: #f67878;
}

.w_all {
  width: 100%;
}

.flex_center_form {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .w_herf {
    width: 340px;
  }
}
</style>
